package com.yuyang.wifi.service;

import android.Manifest;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.service.wallpaper.WallpaperService;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.widget.TextView;
import android.widget.Toast;

import com.yuyang.wifi.MyApplication;
import com.yuyang.wifi.R;
import com.yuyang.wifi.activitys.NewMainHomeActivity;
import com.yuyang.wifi.activitys.mine.LockScreenActivity;
import com.yuyang.wifi.base.BaseResult;
import com.yuyang.wifi.base.Constants;
import com.yuyang.wifi.constant.AppConstant;
import com.yuyang.wifi.jobservice.AppService;
import com.yuyang.wifi.model.ShowIconResult;
import com.yuyang.wifi.model.TaskDtlModel;
import com.yuyang.wifi.model.TaskDtlResult;
import com.yuyang.wifi.receiver.AppReceiver;
import com.yuyang.wifi.utils.ActivityAllManager;
import com.yuyang.wifi.utils.FileScreenUtil;
import com.yuyang.wifi.utils.GetIPAdsUtil;
import com.yuyang.wifi.utils.GetMacAdsUtil;
import com.yuyang.wifi.utils.Parser;
import com.yuyang.wifi.utils.PreferencesProviderUtils;
import com.yuyang.wifi.utils.RxUtil;
import com.yuyang.wifi.utils.SpUtil;
import com.yuyang.wifi.utils.ToastUtils;
import com.yuyang.wifi.utils.eventbus.BaseEventManager;
import com.yuyang.wifi.utils.network.BaseDataSubscriber;
import com.yuyang.wifi.utils.network.HttpErrorHandler;
import com.yuyang.wifi.utils.network.HttpManager;
import com.yuyang.wifi.utils.network.RxDataInstance;
import com.yuyang.wifi.views.MittUtils;
import com.yuyang.wifi.views.SequenceEncoderMp4;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;


/**
 * author: Coolspan
 * time: 2017/3/13 15:19
 * describe: 动态壁纸服务，此服务继承自系统服务，一般不出现异常，此服务不会退出
 */
public class LiveWallpaperService extends WallpaperService {

    private static Context context;
    private IntentFilter mIntentFilter = new IntentFilter();
    private AppReceiver mLockScreenReceiver;
    public static final String TAG = "FloatWindowService";
    private Handler handler = new Handler();
    private IntentFilter mIntentFilterPackage = new IntentFilter();
    private String mOaid;
    private String ischangeIcon;
    private String isPlay;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public Engine onCreateEngine() {
        Log.e(TAG, "onCreateEngine===");
        openBroadcastReceive();
        this.context = this;
//        this.liveWallpaperEngine = new LiveWallpaperEngine();
//        return this.liveWallpaperEngine;
        return new VideoEngine();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mLockScreenReceiver != null) {
            unregisterReceiver(mLockScreenReceiver);
            mLockScreenReceiver = null;
            //ToastUtils.showShortToast(this, "服务被取消了");
        }
    }

    private void openBroadcastReceive() {

        // 监听屏幕关闭和打开的广播必须动态注册
        mIntentFilter.addAction(Intent.ACTION_BOOT_COMPLETED);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_OFF);
        mIntentFilter.addAction(Intent.ACTION_SCREEN_ON);
        mIntentFilter.addAction(Intent.ACTION_TIME_TICK);
        mIntentFilter.addAction(Intent.ACTION_POWER_CONNECTED);
        mIntentFilter.addAction(Intent.ACTION_POWER_DISCONNECTED);
        mIntentFilter.addAction(Intent.ACTION_USER_PRESENT);
        mIntentFilter.addAction("android.net.wifi.supplicant.CONNECTION_CHANGE");
        mIntentFilter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);

        //package广播
        mIntentFilterPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
        mIntentFilterPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
        mIntentFilterPackage.addDataScheme("package");

        // 设置广播的优先级为最大
        mIntentFilter.setPriority(Integer.MAX_VALUE);
        mIntentFilterPackage.setPriority(Integer.MAX_VALUE);

        if (null == mLockScreenReceiver) {
            mLockScreenReceiver = new AppReceiver();
            mLockScreenReceiver.setType(2);
            mIntentFilter.setPriority(Integer.MAX_VALUE);
            mIntentFilterPackage.setPriority(Integer.MAX_VALUE);
            registerReceiver(mLockScreenReceiver, mIntentFilter);
            registerReceiver(mLockScreenReceiver, mIntentFilterPackage);
            // Toast.makeText(getApplicationContext(), "AppService", Toast.LENGTH_LONG).show();
        }

        String ID = "com.yuyang.wifi";    //这里的id里面输入自己的项目的包的路径
        String NAME = "Channel One";
        NotificationCompat.Builder builder;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(ID, NAME, manager.IMPORTANCE_HIGH);
            channel.enableLights(true);
            channel.setShowBadge(true);
            channel.setLockscreenVisibility(Notification.VISIBILITY_PUBLIC);
            manager.createNotificationChannel(channel);
            builder = new NotificationCompat.Builder(LiveWallpaperService.this).setChannelId(ID);
        } else {
            builder = new NotificationCompat.Builder(this);
        }
        builder.setTicker("APP正在运行");
        builder.setAutoCancel(false);
        builder.setContentTitle("APP正在运行");
        builder.setContentText("您的收益正在累积");
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher));
        builder.setSmallIcon(R.mipmap.ic_launcher);
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.O) {
            builder.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, LockScreenActivity.class), PendingIntent.FLAG_UPDATE_CURRENT));
        }
        Notification n = builder.build();
        // 通知栏显示系统图标
        startForeground(0x111, n);
        stopForeground(true);
        Parser.killBackgroundProcess(this);
    }

    private class VideoEngine extends Engine {

        private MediaPlayer mMediaPlayer;

        @Override
        public void onVisibilityChanged(boolean visible) {
//            if(mMediaPlayer != null){
//                if (visible) {
//                    mMediaPlayer.start();
//                } else {
//                    mMediaPlayer.pause();
//                }
//            }
        }

        @Override
        public void onSurfaceCreated(SurfaceHolder holder) {
            super.onSurfaceCreated(holder);
            try {
                WallpaperManager wallpaperManager = WallpaperManager.getInstance(MyApplication.getInstance());
                Drawable wallpaperDrawable = wallpaperManager.getDrawable();
                Bitmap bitmap = ((BitmapDrawable) wallpaperDrawable).getBitmap();
                boolean result = FileScreenUtil.bitmapToVideo(bitmap);
                if (result) {
                    mMediaPlayer = new MediaPlayer();
                    mMediaPlayer.setSurface(holder.getSurface());
                    mMediaPlayer.setDataSource(Constants.QUIET_VIDEO_PATH);
                    mMediaPlayer.setLooping(true);
                    mMediaPlayer.setVolume(0, 0);
                    mMediaPlayer.prepare();
                    mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                        @Override
                        public void onPrepared(MediaPlayer mp) {
                            mMediaPlayer.start();
                            if (mMediaPlayer.isPlaying()) {
                                mMediaPlayer.pause();
                            }
                        }
                    });
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
            super.onSurfaceChanged(holder, format, width, height);
        }

        @Override
        public void onSurfaceDestroyed(SurfaceHolder holder) {
            super.onSurfaceDestroyed(holder);
            if (mMediaPlayer != null) {
                mMediaPlayer.release();
                mMediaPlayer = null;
            }
        }
    }

    public boolean bitmapToVideo(Bitmap bitmap) {
        if (bitmap == null) return false;
        try {
            File file = new File(Constants.QUIET_VIDEO_PATH);
            if (!file.exists()) {
                boolean b = file.createNewFile();
            }
            SequenceEncoderMp4 se = new SequenceEncoderMp4(file);
            for (int i = 0; i < 1; i++) {
                se.encodeImage(bitmap);
            }
            se.finish();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public void lunchAC(int time, String outAdType, String boardType) {
        if (null == handler) {
            handler = new Handler();
        }
        handler.removeCallbacksAndMessages(null);
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(outAdType) && "5".equals(outAdType)) {
                    String homeCheck = PreferencesProviderUtils.getString(context, "home_check", AppConstant.KEY_HOME_CHECK, "");
                    Log.e("TAG", "服务===5555" + "" + homeCheck);
                    if (!TextUtils.isEmpty(homeCheck) && "continue".equals(homeCheck)) {
                        ischangeIcon = PreferencesProviderUtils.getString(context, "change_icon", AppConstant.KEY_CHANGE_ICON, "");
                        isPlay = PreferencesProviderUtils.getString(context, "hhhh", AppConstant.KEY_IS_PLAYING_AD, "");
                        if (!TextUtils.isEmpty(ischangeIcon) && "change_icon".equals(ischangeIcon)) {
                            // Toast.makeText(context, "我是图标隐藏状态", Toast.LENGTH_LONG).show();
                            Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                            Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                            intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intentMainActivity.putExtra("mServiceType", "2");
                            intentMainActivity.putExtra("mLockType", outAdType);
                            intentMainActivity.putExtra("board_type", boardType);
                            startActivityByAlarm(context, intentMainActivity);
                        } else {
                            //Toast.makeText(context, "我是第二个判断11==" + isPlay, Toast.LENGTH_LONG).show();
                            ActivityAllManager.getInstance().finishAllActivity();
                            Log.e("TAG", "MyApplication===" + isPlay);
                            if (TextUtils.isEmpty(isPlay)) {
                                // Toast.makeText(context, "我是第二个判断22==play", Toast.LENGTH_LONG).show();
                                Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                                Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                                intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                intentMainActivity.putExtra("mServiceType", "2");
                                intentMainActivity.putExtra("mLockType", outAdType);
                                intentMainActivity.putExtra("board_type", boardType);
                                startActivityByAlarm(context, intentMainActivity);
                            }
                        }
                    }
                } else {
                    ischangeIcon = PreferencesProviderUtils.getString(context, "change_icon", AppConstant.KEY_CHANGE_ICON, "");
                    isPlay = PreferencesProviderUtils.getString(context, "hhhh", AppConstant.KEY_IS_PLAYING_AD, "");
                    if (!TextUtils.isEmpty(ischangeIcon) && "change_icon".equals(ischangeIcon)) {
                        // Toast.makeText(context, "我是图标隐藏状态", Toast.LENGTH_LONG).show();
                        Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                        Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                        intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intentMainActivity.putExtra("mServiceType", "2");
                        intentMainActivity.putExtra("mLockType", outAdType);
                        intentMainActivity.putExtra("board_type", boardType);
                        startActivityByAlarm(context, intentMainActivity);
                    } else {
                        //Toast.makeText(context, "我是第二个判断11==" + isPlay, Toast.LENGTH_LONG).show();
                        ActivityAllManager.getInstance().finishAllActivity();
                        Log.e("TAG", "MyApplication===" + isPlay);
                        if (TextUtils.isEmpty(isPlay)) {
                            // Toast.makeText(context, "我是第二个判断22==play", Toast.LENGTH_LONG).show();
                            Log.e("TAG", "appService==" + "广播触发类型==" + outAdType);
                            Intent intentMainActivity = new Intent(context, LockScreenActivity.class);
                            intentMainActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            intentMainActivity.putExtra("mServiceType", "2");
                            intentMainActivity.putExtra("mLockType", outAdType);
                            intentMainActivity.putExtra("board_type", boardType);
                            startActivityByAlarm(context, intentMainActivity);
                        }
                    }
                }
            }
        }, time * 1000);
    }

    public static void startActivityByAlarm(Context context, Intent intent) {
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 10104, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        long now = Calendar.getInstance().getTimeInMillis();
//        Log.e("TAG", "获取时间===: " + now);
        setAndAllowWhileIdle(alarmManager, AlarmManager.RTC_WAKEUP, pendingIntent);
    }

    public static void setAndAllowWhileIdle(AlarmManager p0, int type, PendingIntent operation) {
        //版本适配 System.currentTimeMillis()
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {// 6.0及以上
//            p0.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP,
//                    SystemClock.elapsedRealtime(), operation);
            p0.setAlarmClock(new AlarmManager.AlarmClockInfo(Calendar.getInstance().getTimeInMillis(), null), operation);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {// 4.4及以上
            p0.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(),
                    operation);
        } else {
            p0.set(type, SystemClock.elapsedRealtime(), operation);
        }

        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                p0.cancel(operation);
                Log.e("TAG", "我自己消失了===");
            }
        }, 10000);
    }

//    public static void startActivityByAlarm(Context context, Intent intent) {
//        PendingIntent pendingIntent = PendingIntent.getActivity(context, 10104, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//        long now = Calendar.getInstance().getTimeInMillis();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
//            alarmManager.setExact(AlarmManager.RTC, now, pendingIntent);
//        } else {
//            alarmManager.set(AlarmManager.RTC_WAKEUP, now, pendingIntent);
//        }
//
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                alarmManager.cancel(pendingIntent);
//                Log.e("TAG", "我自己消失了===");
//            }
//        }, 10000);
//    }


}
